package com.spring.Transaction;

import com.spring.DB.DBUtil;
import com.spring.springAnnotation.Component;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

//处理数据库连接
public class TransactionManager {
    //线程本地变量：存储当前线程的数据库连接
    private ThreadLocal<Connection> connection = new ThreadLocal<>();
    //开启事务
    public void begin() throws SQLException {
        Connection conn = DBUtil.getConnection();
        conn.setAutoCommit(false); // 关闭自动提交=开启事务
        connection.set(conn);
    }

    //提交事务
    public void commit() throws SQLException {
        Connection conn = connection.get();
        conn.commit();
        conn.close();
        connection.remove();
    }

    //回滚事务
    public void rollback() throws SQLException {
        Connection conn = connection.get();
        conn.rollback();
        conn.close();
        connection.remove();
    }

    public ThreadLocal<Connection> getConnection() {
        return connection;
    }

    public void setConnection(ThreadLocal<Connection> connection) {
        this.connection = connection;
    }
}
